﻿//  -------------------- iSharePoint -------------------- //
// 
//  Company:	IT Complex, LLC
//  Project:	Smart.Common
//  File name:	NotificationItem.cs
//  Developer:	Solomatov Igor
//  Created:	15.04.2012
// 
//  -------------------- iSharePoint -------------------- //

using System;
using Microsoft.SharePoint.Utilities;
using Smart.Common.Entities;
using Smart.Common.Templates;

namespace Smart.Common.Notifications
{
	/// <summary>
	/// Notification item
	/// </summary>
	[Entity(Const.EntityNames.NotificationItem)]
	[ContentType("0x01009BD67413FE6A428BB26A025A6E5D575E")]
	public class NotificationItem : WebEntity, ITemplateInstance
	{
		/// <summary>
		/// Notification addresses (separated by ';')
		/// </summary>
		[Field("NIAddress")]
		public string Address { get; set; }

		/// <summary>
		/// Notification subject
		/// </summary>
		[Field("NISubject")]
		public string Subject { get; set; }

		/// <summary>
		/// Notification body (without leading and trailing HTML tag)
		/// </summary>
		[Field("NIBody")]
		public string Body { get; set; }

		/// <summary>
		/// Notification send retries count
		/// </summary>
		[Field("NIRetriesNo")]
		public int RetriesNo { get; set; }

		/// <summary>
		/// Notification to send at
		/// </summary>
		[Field("NISendAt")]
		public DateTime SendAt { get; set; }

		/// <summary>
		/// Instance data
		/// </summary>
		public object Data { get { return Body; } set { Body = (string)value; } }

		/// <summary>
		/// Sends email
		/// </summary>
		public virtual bool Send()
		{
			var item = GetItem();

			if (item == null)
				return false;

			var web = item.Web;

			if (web == null)
				return false;

			var sended = false;

			try
			{
				sended = SPUtility.SendEmail(web, true, false, Address, Subject, Body, true);

				if (sended || RetriesNo >= Const.TimerJobs.Notification.MaxSendingAttempts)
				{
					Recycle();
				}
				else
				{
					RetriesNo++;
					Save();
				}
			}
			catch (Exception x)
			{
				H.LX("NotificationItem.Send", x);
			}

			return sended;
		}
	}
}